package com.lineage.server.timecontroller.quest;

import com.lineage.server.serverpackets.S_HelpMessage;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.templates.L1QuestUser;
import com.lineage.server.thread.GeneralThreadPool;
import com.lineage.server.world.WorldQuest;
import java.util.Collection;
import java.util.Iterator;
import java.util.TimerTask;
import java.util.concurrent.ScheduledFuture;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class QuestTimer extends TimerTask {
  private static final Log _log = LogFactory.getLog(QuestTimer.class);
  
  private ScheduledFuture<?> _timer;
  
  public void start() {
    int timeMillis = 1000;
    this._timer = GeneralThreadPool.get().scheduleAtFixedRate(this, 1000L, 1000L);
  }
  
  public void run() {
    try {
      Collection<L1QuestUser> allQuest = WorldQuest.get().all();
      if (allQuest.isEmpty())
        return; 
      Iterator<L1QuestUser> iterator = allQuest.iterator();
      while (iterator.hasNext()) {
        L1QuestUser quest = iterator.next();
        if (quest.get_time() > -1) {
          setQuest(quest);
          Thread.sleep(50L);
        } 
      } 
    } catch (Exception e) {
      _log.error("副本任务可执行时间轴异常重启", e);
      GeneralThreadPool.get().cancel(this._timer, false);
      QuestTimer questTimer = new QuestTimer();
      questTimer.start();
    } 
  }
  
  private static void setQuest(L1QuestUser quest) {
    try {
      switch (quest.get_time()) {
        case 60:
        case 120:
        case 180:
        case 240:
        case 300:
        case 600:
        case 900:
        case 1800:
        case 3600:
          quest.sendPackets((ServerBasePacket)new S_HelpMessage("\\fV副本任务-剩余时间：" + (quest.get_time() / 60) + "分"));
          break;
        case 1:
        case 2:
        case 3:
        case 4:
        case 5:
        case 10:
        case 15:
        case 30:
          quest.sendPackets((ServerBasePacket)new S_HelpMessage("\\fV副本任务-剩余时间：" + quest.get_time() + "秒"));
          break;
      } 
      quest.set_time(quest.get_time() - 1);
      if (quest.get_time() == 0) {
        quest.sendPackets((ServerBasePacket)new S_ServerMessage("副本任务-时间结束"));
        quest.set_time(-1);
        quest.endQuest();
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
  }
}
